<?php

namespace app\server;

use Exception;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

class Token
{
    protected string $key;
    protected string $aud;
    protected string $iss;
    protected string $expire;

    public function __construct()
    {
        // 获取token的key
        $this->key    = env('token_key' , 'QUAN');//从配置信息这种获取唯一字符串，你可以随便写
        $this->aud    = env('token_aud' , '');    //面向的用户 可以为空
        $this->iss    = env('token_iss' , '');    //签发者 可以为空
        $this->expire = env('token_expire' , 7200);
    }

    /**
     * 生成token
     *
     * @param int $userId
     *
     * @return string
     */
    public function generateToken(int $userId)
    : string {
        if (empty($userId)) {
            return '';
        }
        $currentTime = time();
        $data        = [
            'iss'  => $this->iss ,
            'aud'  => $this->aud ,
            'iat'  => $currentTime ,
            'nbf'  => $currentTime ,
            'exp'  => $currentTime + $this->expire ,
            'data' => [
                'uid' => $userId ,
            ] ,
        ];

        return JWT::encode($data , $this->key , 'HS256');//生成token 根据参数生成token
    }

    /**
     * 验证token
     *
     * @param string $token
     *
     * @return array
     */
    public function checkToken(string $token)
    : array {
        $data = [
            'code' => 2 ,
            'msg'  => '' ,
            'data' => [] ,
        ];

        try {
            JWT::$leeway   = 60;
            $decoded       = JWT::decode($token , new Key($this->key , 'HS256'));
            $decoded_array = (array)$decoded;
            $data['data']  = $decoded_array['data'];
            $data['code']  = 1;

            return $data;
        } catch (SignatureInvalidException|BeforeValidException|ExpiredException|Exception $e) {
            $data['msg'] = $e->getMessage();

            return $data;
        }
    }
}